/*
 * lab10D1.c
 * CSIS 248 Lab #10
 */

#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>

struct stat statbuffer;

#include "filestruct.h"
#define ARRAY_SIZE 10
int main(int n, char** v){
   if (n < 2){
      printf("%s: Usage: %s <directory>\n\n", v[0], v[0] );
      return -1;
   }
   char* dir = v[1];

   errno = 0;
   lstat( dir, &statbuffer );
   if (errno != 0)
     perror( dir );
   else
      if ( S_ISDIR( statbuffer.st_mode ))
         printf("  %s is a directory\n", dir );
      else {
         printf("  %s is not a directory\n", dir );
         return -2;
      }

   filestruct list[ARRAY_SIZE];
   int position = 0;

   DIR* d = opendir( dir );
   struct dirent* e = NULL;
   do {
      e = readdir( d );
      if (e != NULL){
         printf("     %s\n", e->d_name );
         lstat( e->d_name, &statbuffer );
         if (S_ISREG(statbuffer.st_mode) ) {
            strncpy( list[ position ].name, e->d_name, NAMESIZE);
            list[ position ].size = statbuffer.st_size;
            position++;
         }
      }
   } while (e != NULL);
   closedir( d );

   printf("\n FILES in %s:\n", dir);
   for ( position=0; position<ARRAY_SIZE; position++)
      printf("   %s: %d\n", list[position].name, list[position].size);

   return 0;
}
